<template>
    <div>
        <TableSearch :query="query" :options="searchOpt" :search="handleSearch" />
        <div class="container">
            <TableCustom :columns="columns" :tableData="tableData" :total="page.total"
                :delFunc="handleDelete"
                :changePage="changePage"
                :change-page-size="changePageSize"
                :pageSize="page.page_size"
                :currentPage="page.page"
                :editFunc="handleEdit">
                <template #c_status="{rows}">
                    <el-switch
                        v-model="rows.c_status"
                        :active-value="1"
                        :inactive-value="0"
                        inline-prompt
                        active-text="启用"
                        inactive-text="禁用"
                        @click="chnageUserStatus(rows)"
                        class="ml-2"
                        style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949"
                    />
                </template>
                <template #toolbarBtn>
                    <el-button type="warning" :icon="CirclePlusFilled" @click="addNewUser">新增</el-button>
                    <el-button type="success" :icon="Setting" @click="setUserRole">合作管理员角色配置</el-button>

                </template>
                <template #operator="{ rows }">
                    <el-button type="primary" text size="small"  @click="handleEdit(rows)">
                                    编辑
                    </el-button>
                    <el-button type="danger" text size="small"  @click="handleDelete(rows)">
                        删除
                    </el-button>
                    <el-button type="warning" text size="small"  @click="reserPwd(rows)">
                        重置密码
                    </el-button>
                    <el-button type="primary" text size="small" @click="placeSet(rows)">
                        场地配置
                    </el-button>
                </template>
            </TableCustom>

        </div>
        <el-dialog :title="isEdit ? '编辑' : '新增'" v-model="visible" width="700px" destroy-on-close
            :close-on-click-modal="false" @close="closeDialog">
            <TableEdit :form-data="rowData" :options="options" :edit="isEdit" :update="updateData" :chooseArea="choseP" />
        </el-dialog>
        <el-dialog title="场地配置" v-model="placeVisie" width="620px" destroy-on-close
                :close-on-click-modal="false" @close="closePlaceDialog">
                <el-transfer 
                v-model="bindPlace"
                :titles="['场地列表', '已选择场地列表']"
                filterable
                filter-placeholder="请选择场地"
                :props="{
                    key: 'f_code',
                    label: 'f_field_name',
                }"
                ref="rightPanel"
                :data="allPalce" >
                <template #default="{ option }">
                    <el-tooltip
                        class="box-item"
                        effect="dark"
                        :content="option.f_field_name"
                        placement="top-end"
                    >
                    <span>{{ option.f_field_name }}</span>
                    </el-tooltip>
                </template>
                </el-transfer>
                <el-button style="margin-top: 20px; margin-left: 200px" type="warning" @click="savePlace">保存</el-button>
            </el-dialog>
    </div>
</template>

<script setup lang="ts" name="collaborativeAdministrator-user">
import { ref, reactive } from 'vue';
import { ElMessage, ElMessageBox, ElTransfer, FIRST_LAST_KEYS } from 'element-plus';
import { CirclePlusFilled, Setting } from '@element-plus/icons-vue';
import { User } from './types/cooperUser';
import { fetchCooperationUser, cooperation_user_swtich,
     editAndAddUser,
     query_field_list_cooperation,
     update_cooperation_field,
     cooperation_role_list,
     query_cooperation_field_list,
     update_user_password_cooperation,
      delete_cooperation_user, query_list } from '@/api';
import TableCustom from '@/components/table-custom.vue';
import TableSearch from '@/components/table-search.vue';
import { FormOption, FormOptionList } from '@/types/form-option';
import { useRouter } from 'vue-router';

// 查询相关
const query = reactive({
    c_user_name: '',
    area: '',
});
// 查询条件相关
const searchOpt = ref<FormOptionList[]>([
    { type: 'area', label: '行政区划：', prop: 'area', placeholder: '请选择行政区划'},
    { type: 'input', label: '合作管理员名称：', prop: 'c_user_name', placeholder: '请输入合作管理员名称' }
])
const handleSearch = () => {
    changePage(1);
};

// 表格相关
let columns = ref([
    {type: 'selection'},
    // { type: 'index', label: '序号', width: 55, align: 'center' },
    { prop: 'c_real_user_name', label: '合作管理员名称', width: 140 },
    { prop: 'c_user_name', label: '合作管理员账户', width: 180 },
    { prop: 'y_role_name', label: '合作管理员角色', width: 160 },
    { prop: 'f_names', label: '所属场地', width: 180 , showOverflowTooltip: true},
    { prop: 'c_contacts_name', label: '联系人姓名', width: 120 },
    { prop: 'c_contacts_phone', label: '联系人电话', width: 140 },
    { prop: 'c_contacts_area', label: '联系地址', width: 200 },
    { prop: 'custom', label: '行政区划', props: 'c_province,c_city,c_area' , width: 120 },
    { prop: 'c_superior_name', label: '上级管理员', width: 120 },
    { prop: 'c_status', label: '用户状态', width: 100 },
    { prop: 'operator', label: '操作', width: 350 },
])
const page = reactive({
    page: 1,
    page_size: 10,
    total: 0,
})
const tableData = ref<User[]>([]);
const getData = async () => {
    let obj = {c_province: null, c_city: null, c_area: null}
    if (query.area.length) {
        obj.c_province = query.area[0]
        obj.c_city = query.area[1]
        obj.c_area = query.area[2]
    }
    
    const res = await fetchCooperationUser({page: page.page, page_size: page.page_size, c_user_name: query.c_user_name, ...obj })
    tableData.value = res.data.data_list;
    page.total = res.data.total;
};
getData();

const chnageUserStatus = (rows) => {
    cooperation_user_swtich({c_u_code: rows.c_u_code, c_status: rows.c_status}).then(res => {
        if(res.code === '1000') {
            ElMessage.success('用户状态更新成功')
        } else {
            rows.c_status = rows.c_status == 0 ? 1 : 0
        }
    })
}

const router = useRouter();

const setUserRole = () => {
    router.push({
        path: '/collaborativeAdministrator-role',
    });
}

const addNewUser = async() => {
    let cooperation_user = await query_list({"filter":"cooperation_user"})
    options.value.list[0].opts = cooperation_user.data
    options.value.list[2].disabled = false
    let primsCoorData =  await cooperation_role_list()
    options.value.list[3].opts = primsCoorData.data
    visible.value = true;
}

const changePage = (val: number) => {
    page.page = val;
    getData();
};
const changePageSize = (val: number) => {
    page.page_size = val;
    getData();
};
const isEdit = ref(false);
// 新增/编辑弹窗相关
let options = ref<FormOption>({
    labelWidth: '150px',
    span: 20,
    list: [
        { type: 'select', label: '上级合作管理员', prop: 'c_superior_code', required: false, placeholder: '请选择上级合作管理员',opts: [], labelItem: 'c_user_name', valueItem: 'c_u_code' },
        { type: 'input', label: '合作管理员名称', prop: 'c_real_user_name', required: true, placeholder: '请输入合作管理员名称' },
        { type: 'input', label: '合作管理员账户', prop: 'c_user_name', required: true, placeholder: '请输入合作管理员账户', tips: '请输入手机号格式'},
        { type: 'select', label: '合作管理员角色', prop: 'c_role', required: true, placeholder: '请选择角色',opts: [], labelItem: 'y_role_name', valueItem: 'y_role_code' },
        { type: 'input', label: '联系人姓名', prop: 'c_contacts_name', required: true, placeholder: '请输入联系人姓名' },
        { type: 'input', label: '联系人电话', prop: 'c_contacts_phone', required: true, placeholder: '请输入联系人电话' },
        { type: 'input', label: '联系人地址', prop: 'c_contacts_area', required: true, placeholder: '请输入联系人地址' },
        { type: 'custom_area', label: '行政区划', prop: 'custom_area', required: true, placeholder: '请选择行政区划' },
        { type: 'select', label: '所属银行', prop: 'c_bank_name', required: false, placeholder: '请选择所属银行' },
        { type: 'input', label: '结算账户', prop: 'c_bank_account', required: false, placeholder: '请输入合作结算账户' },
        { type: 'input', label: '结算账号', prop: 'c_bank_code', required: false, placeholder: '请输入结算账号' },
        { type: 'input', label: '支行名称', prop: 'c_bank_real_name', required: false, placeholder: '请输入支行名称' },
        { type: 'textarea', label: '备注', prop: 'c_remarks', required: false, placeholder: '请输入备注' },
    ]
})
const visible = ref(false);

const rowData = ref({});
const handleEdit = async(row) => {
    console.log(row)
    row.custom_area = [`${row.c_province}`, `${row.c_city}`, `${row.c_area}`];
    let primsCoorData =  await cooperation_role_list()
    let cooperation_user = await query_list({"filter":"cooperation_user"})
    options.value.list[0].opts = cooperation_user.data
    options.value.list[2].disabled = true
    options.value.list[3].opts = primsCoorData.data
    rowData.value = { ...row };
    isEdit.value = true;
    visible.value = true;
};
const choseP = (data, value) => {
    data.c_province = value[0]
	data.c_city = value[1]
	data.c_area = value[2]
}
const updateData = async(value) => {
    const {c_u_code, c_superior_code, c_real_user_name, c_user_name, c_contacts_name, c_contacts_phone, c_contacts_area, c_province, c_city,c_area, c_bank_name, c_bank_account, c_bank_code, c_bank_real_name, c_remarks, c_role  } = value
    options.value.list[2].disabled = false
    const sentData = JSON.parse(JSON.stringify(value))
    delete sentData.custom_area
    delete sentData.c_status
    delete sentData.create_time
    delete sentData.update_time
    const res = await editAndAddUser({c_u_code, c_superior_code: c_superior_code || '', c_real_user_name, c_user_name, c_contacts_name, c_contacts_phone, c_contacts_area, c_province, c_city,c_area, c_bank_name, c_bank_account, c_bank_code, c_bank_real_name, c_remarks, c_role  })
    if (res.code == '1000') {
        closeDialog();
        getData();
    }

};

const closeDialog = () => {
    visible.value = false;
    isEdit.value = false;
};

// 查看详情弹窗相关
const visible1 = ref(false);
const viewData = ref({
    row: {},
    list: []
});

// 删除相关
const handleDelete = (row) => {
    ElMessageBox.confirm('确定要删除吗？', '提示', {
        type: 'warning'
    })
        .then(async () => {
            delete_cooperation_user({c_u_code: row.c_u_code }).then(res => {
            if (res.code == '1000') {
                getData();
                ElMessage.success('删除成功');
            }
        })
        })
        .catch(() => { });
}
const reserPwd = (row) => {
    ElMessageBox.confirm('确定要重置密码吗？', '提示', {
        type: 'warning'
    })
        .then(async () => {
            update_user_password_cooperation({c_u_code: row.c_u_code}).then(res => {
                if(res.code == '1000') {
                    ElMessage.success('重置密码成功')
                }
            })
        })
        .catch(() => { });
}
// 场地配置

const placeVisie = ref(false)
const u_user_code = ref('')
const allPalce = ref([])
const userPlace = ref([])
const bindPlace = ref([]) 

const rightPanel = ref<InstanceType<typeof ElTransfer>>()
const closePlaceDialog = () => {
    bindPlace.value = []
    placeVisie.value = false
}
const placeSet = async (row) => {
    u_user_code.value = row.c_u_code
    let placeRes = await query_field_list_cooperation()
    allPalce.value = placeRes.data
    let useP = await query_cooperation_field_list({u_user_code: u_user_code.value})
    userPlace.value = useP.data
    if (userPlace.value.length > 0) {
        userPlace.value.forEach(item => {
            bindPlace.value.push(item.f_code)
        })
    } else {
        bindPlace.value = []
    }
    placeVisie.value = true
}
const savePlace = () => {
    let sendValue = []
    allPalce.value.forEach(item => {
        bindPlace.value.forEach(code => {
            if (code == item.f_code) {
                sendValue.push(item)
            }
        })
    })
    update_cooperation_field({
        u_user_code: u_user_code.value,
        field_list: sendValue
    }).then(res => {
        if(res.code == '1000') {
            ElMessage.success('配置成功')
            placeVisie.value = false
        }
    })
    

}
</script>

<style scoped></style>